package com.weiweiqin.controller.back;

import cn.ucloud.usms.*;
import cn.ucloud.usms.Signature;
import com.weiweiqin.model.UserMobileSource;
import com.weiweiqin.service.UserMobileSourceService;
import com.weiweiqin.utils.MobileFromUtil;
import com.weiweiqin.utils.ReadExcelUtils;
import com.weiweiqin.vo.common.Page;
import com.weiweiqin.vo.common.Result;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.methods.HttpGet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.*;

@Controller
@RequestMapping("admin/userMobileSource")
public class UserMobileSourceController {

	private static final Logger logger = LoggerFactory.getLogger(UserMobileSourceController.class);
	@Autowired
	private UserMobileSourceService userMobileSourceService;	

	@RequestMapping(value = "/importFileToData.do", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public String importFileToData() {
		Result result = new Result();
		logger.error("Enter method importFileToData...");
		try {
			long t = System.currentTimeMillis();
			ArrayList<ArrayList<Object>> result1 = new ReadExcelUtils().readExcelByColumn("D://order.xls", new int[] {0, 1,2});
			System.out.println(System.currentTimeMillis() - t);
			for (int i = 0; i < result1.size(); i++) {
				UserMobileSource userMobileSource = new UserMobileSource();;
				for (int j = 0; j < result1.get(i).size(); j++) {
					String column = result1.get(i).get(j).toString();
					if(j == 0) {
						userMobileSource.setName(column);
					}else if(j == 1) {
						userMobileSource.setMobile(column);
					}else if(j == 2) {
						userMobileSource.setAddr(column);
					}
				}
				userMobileSource.setPinfo("");
				userMobileSource.setOrigin("chd");
//				userMobileSource.setOstatus(1);
				userMobileSource.setSendnum(0);
				if(!StringUtils.isEmpty(userMobileSource.getMobile()) && userMobileSource.getMobile().length() == 11 && userMobileSource.getName().length() <= 6) {
					userMobileSourceService.save(userMobileSource);
				}
			}
		} catch (Exception e) {
			logger.error("数据库异常...", e);
			result.setResult(false);
			result.setErrorMsg("数据库异常。。。");
			return result.toJson();
		}
		result.setErrorMsg("success");
		result.setResult(true);
		return result.toJson();
	}

	@RequestMapping(value = "/pageList.do", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public String pageList(int currPage){
		Result result = new Result();
		try {
			Page page = new Page();
			page.setCurrPage(currPage);
			List<UserMobileSource> userMobileSourceList = userMobileSourceService.pageList(page, null);
			int totalCount = userMobileSourceService.totalCount(null);
			Map<String, Object> mp = new HashMap<>();
			mp.put("list", userMobileSourceList);
			mp.put("totalCount", totalCount);
			result.setObj(mp);
		} catch (Exception e) {
			logger.error("数据库异常...", e);
			result.setResult(false);
			result.setErrorMsg("数据库异常。。。");
			return result.toJson();
		}
		result.setResult(true);
		return result.toJson();
	}

	@RequestMapping(value = "/updateMobileRegion.do", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public String updateMobileRegion() {
		Result result = new Result();
		logger.error("Enter method updateMobileRegion...");
		try {
			 for(int i =1;i<101;i++) {
				 UserMobileSource userMobileSource = userMobileSourceService.get(i);
				 if(null != userMobileSource) {
					 if(StringUtils.isEmpty(userMobileSource.getMobileRegion())) {
						 String mobileFrom = MobileFromUtil.getMobileFrom(userMobileSource.getMobile());
						 if(!StringUtils.isEmpty(mobileFrom)) {
							 String[] split = mobileFrom.split("_");
							 userMobileSource.setMobileRegion(split[0]);
							 userMobileSource.setMobileType(split[1]);
							 userMobileSourceService.update(userMobileSource);
					 }

					 }
				 }

			 }
		} catch (Exception e) {
			logger.error("数据库异常...", e);
			result.setResult(false);
			result.setErrorMsg("数据库异常。。。");
			return result.toJson();
		}
		result.setErrorMsg("success");
		result.setResult(true);
		return result.toJson();
	}

	@RequestMapping(value = "/sendMsgToMobile.do", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public String sendMsgToMobile() {
		Result result = new Result();
		logger.error("Enter method sendMsgToMobile...");
		try {
			Page page = new Page();
			page.setCurrPage(1);
			page.setPageSize(50);
			List<UserMobileSource> userMobileSources = userMobileSourceService.pageList(page, new HashMap<String, Object>());

			List<String> phoneNumbers = new ArrayList<>();
			for (UserMobileSource userMobileSource : userMobileSources) {
				if(!StringUtils.isEmpty(userMobileSource.getMobile()) && !StringUtils.isEmpty(userMobileSource.getMobileRegion()) && userMobileSource.getSendnum() == 0 && userMobileSource.getOstatus() == 1) {
					phoneNumbers.add(userMobileSource.getMobile());
				}
			}
//			phoneNumbers.add("13666067037");
//			phoneNumbers.add("15759270564");
			System.out.println(phoneNumbers);
			//get 方式一次最多200个号码
			BaseRequestParam param = new SendUSMSMessageParam(phoneNumbers,"UTB19072859196A");
			param.setAction("SendUSMSMessage");
			param.setPublicKey("+CyVLxLkDjf4cJ8PPin0OLQEXCA7Sv46FGGS49vXbcGmbmWmrKNdm4OaFFc=");
			Account account = new Account("z3EEZ5Ycs9hVvjMva7Dz3pLQvZJzjUGiZ1YmjCNwaXGEWo3dR98koL+mEkcsbYYS","+CyVLxLkDjf4cJ8PPin0OLQEXCA7Sv46FGGS49vXbcGmbmWmrKNdm4OaFFc=");
			List<Param> paramList = ObjectToParam.objectToParams(param);
			// 获取签名字符串
			String signature = Signature.getSignature(paramList, account);
			// url编码
			Signature.urlEncodeParams(paramList);

			// 构造url参数
			StringBuilder builder = new StringBuilder();
			for (Param param1 : paramList) {
				if (StringUtils.isBlank(param1.getParamKey())){
					continue;
				}
				builder.append(param1.getParamKey() + "=" + param1.getParamValue() + "&");
			}
			// 设置签名
			builder.append("Signature" + "=" + signature);

			String urlPara = builder.toString();

			String apiUrl = "https://api.ucloud.cn";
			System.out.println(urlPara);

			final HttpGet get = new HttpGet(apiUrl + "?" + urlPara);

			Http http = new Http(SendUSMSMessageResult.class);

			BaseResponseResult msgResult = http.doHttp(get, null,false);
			//发送成功,更新对应号码发送次数
			if(msgResult.getRetCode() == 0) {
				for (UserMobileSource userMobileSource : userMobileSources) {
					if(!StringUtils.isEmpty(userMobileSource.getMobile()) && !StringUtils.isEmpty(userMobileSource.getMobileRegion()) && userMobileSource.getSendnum() == 0 && userMobileSource.getOstatus() == 1) {
						userMobileSource.setSendnum(userMobileSource.getSendnum() +1);
						userMobileSourceService.update(userMobileSource);
					}
				}

			}


		} catch (Exception e) {
			logger.error("数据库异常...", e);
			result.setResult(false);
			result.setErrorMsg("数据库异常。。。");
			return result.toJson();
		}
		result.setErrorMsg("success");
		result.setResult(true);
		return result.toJson();
	}
}
